var bookService = null;
$(document).ready(function(){
    $("#bookList").change(loadSelectedBook);
    // create prime service, outputService is exported to this service
    webrpc.load("bookService.js", function(services, error){
        bookService = services.bookService;
        $(":button:disabled").attr("disabled", false);
	showAllBooks();
    });
});
    function notify(msg) {
	$("#notifyMessage").html(msg).show().fadeOut(2000);
    }
    var selectedBookId;
    function loadSelectedBook() {
	var selected = $("#bookList option:selected")[0];
	selectedBookId = selected.value;
	bookService.get(selectedBookId, function(book) {
	    $("#title").val(book.title);
	    $("#price").val(book.price);
	});
    }
    function createBook() {
	saveBook(null);
    }
    function updateBook() {
	saveBook(selectedBookId);
    }
    function saveBook(bookId) {
	bookService.save({
	    id: bookId,
	    title: $("#title").val(),
	    price: $("#price").val()
	}, function(savedBook) {
	    notify("Saved successfully");
	    showAllBooks(function() {
		selectedBookId = savedBook.id;
		$("#bookList option[value=" + selectedBookId + "]").attr("selected", true);
	    });
	});
    }
    function deleteBook() {
	if (selectedBookId) {
	    bookService.remove(selectedBookId, function() {
		notify("Deleted successfully");
		showAllBooks(function() {
		    selectedBookId = null;
		});
	    });
	}
    }
    function showAllBooks(callback) {
	bookService.getAll(function(books) {
	    var bookList = $("#bookList").empty()[0].options;
	    selectedBookId = null;
	    for (var i = 0; i < books.length; i++) {
		bookList[bookList.length] = new Option(books[i].title, books[i].id);
	    }
	    if (callback)
		callback();
	});
    }
